package com.suxin.algorithm.table;

import com.google.common.collect.Range;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.RangeShardingAlgorithm;

import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @classname GoodsTableCreateTimeRangeShardingAlgorithm
 * @description [ 范围 ]
 * @date 2021/5/18 13:50
 */
public class GoodsTableCreateTimeRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        Set<String> set = new HashSet<>(10);
        // 逻辑表名字
        String logicTableName = rangeShardingValue.getLogicTableName() + "_";
        Range<Date> valueRange = rangeShardingValue.getValueRange();
        // 起始值
        Date lowerEndpoint = valueRange.lowerEndpoint();
        int lowerYear = lowerEndpoint.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
        set.add(String.valueOf(lowerYear));
        // 结束值
        Date upperEndpoint = valueRange.upperEndpoint();
        int upperYear = upperEndpoint.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
        set.add(String.valueOf(upperYear));
        Set<String> collect = set.stream().map(item -> logicTableName + item).collect(Collectors.toSet());
        collect.retainAll(collection);
        return collect;
    }

}